<?php
function curl_file_get_contents($url, $timeout = 5000, $ssl = false)
{
    if (function_exists ( "curl_init" )) {
        $ch = curl_init ();
        curl_setopt ( $ch, CURLOPT_URL, $url );
        curl_setopt ( $ch, CURLOPT_TIMEOUT, $timeout );
        if ($ssl)
            curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, false );
        if (isset ( $_SERVER ['HTTP_USER_AGENT'] ))
            curl_setopt ( $ch, CURLOPT_USERAGENT, $_SERVER ['HTTP_USER_AGENT'] );
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
        $r = curl_exec ( $ch );
        curl_close ( $ch );
    } else {
        $r = @file_get_contents ( $url );
    }

    return $r;
}

/**
 * 判断是否SSL协议
 * @return boolean
 */
function is_ssl() {
    if(isset($_SERVER['HTTPS']) && ('1' == $_SERVER['HTTPS'] || 'on' == strtolower($_SERVER['HTTPS']))){
        return true;
    }elseif(isset($_SERVER['SERVER_PORT']) && ('443' == $_SERVER['SERVER_PORT'] )) {
        return true;
    }
    return false;
}

/**
 * 字符串加密、解密函数
 * @param	string	$txt		字符串
 * @param	string	$operation	ENCODE为加密，DECODE为解密，可选参数，默认为ENCODE，
 * @param	string	$key		密钥：数字、字母、下划线
 * @param	string	$expiry		过期时间
 * @return	string
 */
function str_auth($string, $operation = 'ENCODE', $key = '', $expiry = 0) {
    $ckey_length = 4;
    $key = md5($key!=''?$key:C('AUTH_KEY'));
    $keya = md5(substr($key, 0, 16));
    $keyb = md5(substr($key, 16, 16));
    $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : '';

    $cryptkey = $keya.md5($keya.$keyc);
    $key_length = strlen($cryptkey);

    $string = $operation == 'DECODE' ? base64_decode(strtr(substr($string, $ckey_length), '-_', '+/')) : sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;
    $string_length = strlen($string);

    $result = '';
    $box = range(0, 255);

    $rndkey = array();
    for($i = 0; $i <= 255; $i++) {
        $rndkey[$i] = ord($cryptkey[$i % $key_length]);
    }

    for($j = $i = 0; $i < 256; $i++) {
        $j = ($j + $box[$i] + $rndkey[$i]) % 256;
        $tmp = $box[$i];
        $box[$i] = $box[$j];
        $box[$j] = $tmp;
    }

    for($a = $j = $i = 0; $i < $string_length; $i++) {
        $a = ($a + 1) % 256;
        $j = ($j + $box[$a]) % 256;
        $tmp = $box[$a];
        $box[$a] = $box[$j];
        $box[$j] = $tmp;
        $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
    }

    if($operation == 'DECODE') {
        if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {
            return substr($result, 26);
        } else {
            return '';
        }
    } else {
        return $keyc.rtrim(strtr(base64_encode($result), '+/', '-_'), '=');
    }
}
//安全过滤函数
function safe_filter(&$value){
    $value=str_replace(array('%20','%27','%2527','*','"',"'",';','<','>','{','}','\\'),'',strtolower($value));
}
/**
 * xss过滤函数
 *
 * @param $string
 * @return string
 */
function remove_xss($string) {
    $string = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]+/S', '', $string);

    $parm1 = Array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');

    $parm2 = Array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');

    $parm = array_merge($parm1, $parm2);

    for ($i = 0; $i < sizeof($parm); $i++) {
        $pattern = '/';
        for ($j = 0; $j < strlen($parm[$i]); $j++) {
            if ($j > 0) {
                $pattern .= '(';
                $pattern .= '(&#[x|X]0([9][a][b]);?)?';
                $pattern .= '|(&#0([9][10][13]);?)?';
                $pattern .= ')?';
            }
            $pattern .= $parm[$i][$j];
        }
        $pattern .= '/i';
        $string = preg_replace($pattern, ' ', $string);
    }
    return $string;
}

/**
 * 获取和设置配置参数 支持批量定义
 * @param string|array $name 配置变量
 * @param mixed $value 配置值
 * @return mixed
 * strtolower -- 将字符串转化为小写;
 * array_change_key_case — 返回字符串键名全为小写或大写的数组
 */
function C($name=null, $value=null) {
    static $_config = array();
    if (empty($name)) return $_config;
    if (is_string($name)) {
       $name = strtolower($name);
       if (is_null($value))  return isset($_config[$name]) ? $_config[$name] : false;
       $_config[$name] = $value;
       return;
    }
    // 批量设置
    if (is_array($name)){
        $_config = array_merge($_config, array_change_key_case($name));
        return;
    }
    return false; // 避免非法参数
}
//自动加载函数
function loader($class){
    if(is_file(LIB_PATH.$class.'.class.php')) include_once  LIB_PATH.$class.'.class.php';
    else{
        if(defined('M_PATH')&&is_file(M_PATH.'lib'.DS.$class.'.class.php'))
            include_once M_PATH.'lib'.DS.$class.'.class.php';
    }
}

/**
 * 获取客户端IP地址
 * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @return mixed
 */
function get_client_ip($type = 0,$adv=false){
    $type = $type ? 1 : 0;
    static $ip = NULL;
    if ($ip !== NULL)
        return $ip [$type];
    if (isset ( $_SERVER ['HTTP_X_FORWARDED_FOR'] )) {
        $arr = explode ( ',', $_SERVER ['HTTP_X_FORWARDED_FOR'] );
        $pos = array_search ( 'unknown', $arr );
        if (false !== $pos)
            unset ( $arr [$pos] );
        $ip = trim ( $arr [0] );
    }
    if (isset ( $_SERVER ['HTTP_CLIENT_IP'] )) {
        $ip = $_SERVER ['HTTP_CLIENT_IP'];
    }
    if (isset ( $_SERVER ['REMOTE_ADDR'] )) {
        $ip = $_SERVER ['REMOTE_ADDR'];
    }
    if (isset ( $_SERVER ['HTTP_X_CLIENTIP'] )) {
        $ip = $_SERVER ['HTTP_X_CLIENTIP'];
    }
    // IP地址合法验证
    $long = sprintf ( "%u", ip2long ( $ip ) );
    $ip = $long ? array ($ip, $long ) : array ('0.0.0.0', 0 );
    return $ip [$type];
}
/**
 * 发送HTTP状态
 * @param integer $code 状态码
 * @return void
 */
function send_http_status($code) {
    static $_status = array(
        // Informational 1xx
        100 => 'Continue',
        101 => 'Switching Protocols',
        // Success 2xx
        200 => 'OK',
        201 => 'Created',
        202 => 'Accepted',
        203 => 'Non-Authoritative Information',
        204 => 'No Content',
        205 => 'Reset Content',
        206 => 'Partial Content',
        // Redirection 3xx
        300 => 'Multiple Choices',
        301 => 'Moved Permanently',
        302 => 'Moved Temporarily ',  // 1.1
        303 => 'See Other',
        304 => 'Not Modified',
        305 => 'Use Proxy',
        // 306 is deprecated but reserved
        307 => 'Temporary Redirect',
        // Client Error 4xx
        400 => 'Bad Request',
        401 => 'Unauthorized',
        402 => 'Payment Required',
        403 => 'Forbidden',
        404 => 'Not Found',
        405 => 'Method Not Allowed',
        406 => 'Not Acceptable',
        407 => 'Proxy Authentication Required',
        408 => 'Request Timeout',
        409 => 'Conflict',
        410 => 'Gone',
        411 => 'Length Required',
        412 => 'Precondition Failed',
        413 => 'Request Entity Too Large',
        414 => 'Request-URI Too Long',
        415 => 'Unsupported Media Type',
        416 => 'Requested Range Not Satisfiable',
        417 => 'Expectation Failed',
        // Server Error 5xx
        500 => 'Internal Server Error',
        501 => 'Not Implemented',
        502 => 'Bad Gateway',
        503 => 'Service Unavailable',
        504 => 'Gateway Timeout',
        505 => 'HTTP Version Not Supported',
        509 => 'Bandwidth Limit Exceeded'
    );
    if(isset($_status[$code])) {
        header('HTTP/1.1 '.$code.' '.$_status[$code]);
        // 确保FastCGI模式下正常
        header('Status:'.$code.' '.$_status[$code]);
    }
}

/**
 * 返回经addslashes处理过的字符串或数组
 * @param $string 需要处理的字符串或数组
 * @return mixed
 * new_addslashes-- 使用反斜线引用字符串,addslashes的增强版2
 */
function new_addslashes($string) {
    if(!is_array($string)) return addslashes($string);
    foreach($string as $key => $val) $string[$key] = new_addslashes($val);
    return $string;
}

/**
 * 返回经stripslashes处理过的字符串或数组
 * @param $string 需要处理的字符串或数组
 * @return mixed
 * stripslashes() 函数删除由 addslashes() 函数添加的反斜杠。
 */
function new_stripslashes($string) {
    if(!is_array($string)) return stripslashes($string);
    foreach($string as $key => $val) $string[$key] = new_stripslashes($val);
    return $string;
}

//数据库连接
function db($db_config='db1'){
    $db=new Db();
    return $db->getInstance($db_config);
}
//创建目录
function mkDirs($dir){
    if(!is_dir($dir)){
        if(!mkDirs(dirname($dir))){
            return false;
        }
        if(!mkdir($dir,0777)){
            return false;
        }
    }
    return true;
}
 /**
 * 根据半正失公式，获取两地理坐标之间的距离
 *
 * @param integer 坐标1经度
 * @param integer 坐标1纬度
 * @param integer 坐标2经度
 * @param integer 坐标2纬度
 * @return integer 两坐标之间的距离，以KM为单位
 */
function distance($lng1, $lat1, $lng2 ,$lat2)
{
	//$r = 6371.137;
	$r = 6378.137;
	$dlat = deg2rad($lat2 - $lat1);
	$dlng = deg2rad($lng2 - $lng1);

	$a = pow(sin($dlat / 2), 2) +
		 cos(deg2rad($lat1)) * cos(deg2rad($lat2)) *
		 pow(sin($dlng / 2), 2);

	$c = 2 * atan2(sqrt($a), sqrt(1 - $a));
	$s = $r * $c;
	return round($s,2);
}

//GCJ-02(火星，高德) 坐标转换成 BD-09(百度) 坐标
  //@param bd_lon 百度经度
//@param bd_lat 百度纬度
function bd_encrypt($gg_lon,$gg_lat)
{
	$x_pi = 3.14159265358979324 * 3000.0 / 180.0;
	$x = $gg_lon;
	$y = $gg_lat;
	$z = sqrt($x * $x + $y * $y) - 0.00002 * sin($y * $x_pi);
	$theta = atan2($y, $x) - 0.000003 * cos($x * $x_pi);
	$data['bd_lon'] = $z * cos($theta) + 0.0065;
	$data['bd_lat'] = $z * sin($theta) + 0.006;
	return $data;
}
//BD-09(百度) 坐标转换成  GCJ-02(火星，高德) 坐标
  //@param bd_lon 百度经度
//@param bd_lat 百度纬度
function bd_decrypt($bd_lon,$bd_lat)
{
	$x_pi = 3.14159265358979324 * 3000.0 / 180.0;
	$x = $bd_lon - 0.0065;
	$y = $bd_lat - 0.006;
	$z = sqrt($x * $x + $y * $y) - 0.00002 * sin($y * $x_pi);
	$theta = atan2($y, $x) - 0.000003 * cos($x * $x_pi);
	$data['gg_lon'] = $z * cos($theta);
	$data['gg_lat'] = $z * sin($theta);
	return $data;
}

/**
 * curl POST文件
 * @param type $url
 * @param type $postField
 * @param type $timeout
 * @return type
 */
function curl_post_contents($url, $postField, $timeout = 30)
{
    $ch = curl_init ();
    curl_setopt ( $ch, CURLOPT_URL, $url );
    curl_setopt ( $ch, CURLOPT_POST, 1 );
    curl_setopt ( $ch, CURLOPT_POSTFIELDS, $postField );
    curl_setopt ( $ch, CURLOPT_TIMEOUT, $timeout );
    if (isset ( $_SERVER ['HTTP_USER_AGENT'] ))
        curl_setopt ( $ch, CURLOPT_USERAGENT, $_SERVER ['HTTP_USER_AGENT'] );
    curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, 1 );
    $r = curl_exec ( $ch );
    curl_close ( $ch );
    return $r;
}
